<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 获取access token逻辑
 * @author  :  Calvin <dev@skiy.net>
 */

class Token_service extends MY_Service {


    public function __construct() {
        parent::__construct();
        $this->load->library("encrypt");
    }

    /**
     * 获取token
     * @param bool|FALSE $temp_token
     * @return mixed
     */
    public function get_access_token($temp_token=FALSE){
        $this->session->sess_regenerate(!$temp_token);
        $sid = $this->session->session_id;
        $time = time();
        $data = array("time"=>$time,"temp"=>$temp_token,"ip_address"=>$this->input->ip_address());
        $this->session->set_userdata($this->config->item("rest_access_token_session_key"),$data);
        //$this->encrypt->set_cipher(MCRYPT_RC2);
        //$sess_access_token = $this->encrypt->encode($sid);
        return $sid;
    }


    /**
     * 解析token
     * @param $token
     * @return bool 如果值是true则返回sid
     */
    public function parse_token($token){
        if($token){
            //$this->encrypt->set_cipher(MCRYPT_RC2);
            //$info = $this->encrypt->decode($token);
            //$info = @json_decode($info,TRUE);
            //return $this->token_valid($info);
            return $token;
        }
        return $this->set_error(1015);
    }

    /**
     * token信息校验
     * @param $token_info
     * @return bool
     */
    public function token_valid(){
        $sess_key = config_item("rest_access_token_session_key");
        $token_info = $this->session->userdata($sess_key);
        $exp = $token_info['temp']?config_item("rest_temp_access_token_expire"):config_item("rest_access_token_expire");
        $ip_address = $this->input->ip_address();
        if(time()-$token_info['time']<$exp && $ip_address == $token_info['ip_address']){
            if(config_item("rest_access_token_auto_update"))
            {
                $token_info['time']=time();
                $this->session->set_userdata($sess_key,$token_info);
            }
            if($token_info['temp']){
                $this->session->sess_regenerate(TRUE);
            }
            return TRUE;
        }else{
            return $this->set_error(1015);
        }
    }


    public function check_secret($client_id,$client_secret){
        $secret_list = $this->config->item("rest_access_secret");
        return isset($secret_list[$client_id]) && $secret_list[$client_id]===$client_secret;
    }

}